package com.b2c.repository.oms;

import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.vo.OrderImportPiPiEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * 批批网订单
 */
@Repository
public class DcPiPiOrderRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 导入批批网订单
     *
     * @param orderList   订单列表
     * @param buyerUserId 客户userId
     * @return
     */
    @Transactional
    public ResultVo<String> importExcelOrderForPiPi(List<OrderImportPiPiEntity> orderList, Integer buyerUserId) {
        if (orderList == null || orderList.size() == 0)
            return new ResultVo<>(EnumResultVo.DataError, "参数错误：缺少orderList","");
//        if (buyerUserId == null || buyerUserId == 0)
//            return new ResultVo<>(EnumResultVo.DataError, "参数错误：缺少buyerUserId","");

//        UserEntity buyerUser = new UserEntity();
//        try {
//            //查询客户数据
//            buyerUser = jdbcTemplate.queryForObject("SELECT * FROM " + Tables.User + " WHERE id=?", new BeanPropertyRowMapper<>(UserEntity.class), buyerUserId);
//        } catch (Exception e) {
//            return new ResultVo<>(EnumResultVo.DataError, "参数错误：buyerUserId找不到客户","");
//        }

        /*******插入数据********/
        int totalInsert = 0;//新增数量
        int totalExist = 0;//已存在数量
        int totalError = 0;//错误数量
        for (var order : orderList) {
            //查询订单是否存在
            var oList = jdbcTemplate.query("SELECT * FROM dc_pipi_order WHERE orderNum=? ", new BeanPropertyRowMapper<>(OrderImportPiPiEntity.class), order.getOrderNum());

            if (oList != null && oList.size() > 0) {
                //已经存在
                totalExist++;
            } else {

                try {
                    /**************1、新增order**********************/
                    Integer shopId = 9;
                    //商品总价
                    double goodsTotalAmount = 0.0;
                    for (var item : order.getItems()) {
                        goodsTotalAmount += item.getPrice().doubleValue() * item.getQuantity();
                    }

//                    //订单状态为待发货
//                    int status = EnumErpOrderStatus.WaitSend.getIndex();
//                    String statusStr = "待发货";

                    StringBuilder insertSQL = new StringBuilder();
                    insertSQL.append("INSERT INTO dc_pipi_order ");
                    insertSQL.append(" (shopId,orderNum,buyerName,totalAmount,sellerMemo,contactPerson,contactMobile,province,city,area,address,payMethod,statusStr,status,auditStatus,createOn,orderTime)");
                    insertSQL.append(" VALUE (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ");

                    KeyHolder keyHolder = new GeneratedKeyHolder();


                    double finalGoodsTotalAmount = goodsTotalAmount;
                    jdbcTemplate.update(new PreparedStatementCreator() {
                        @Override
                        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                            PreparedStatement ps = connection.prepareStatement(insertSQL.toString(), Statement.RETURN_GENERATED_KEYS);
                            ps.setInt(1,shopId);
                            ps.setString(2,  order.getOrderNum());
                            ps.setString(3, order.getContactPerson());
                            ps.setBigDecimal(4, BigDecimal.valueOf(finalGoodsTotalAmount));
                            ps.setString(5, order.getSellerMemo());
                            ps.setString(6, order.getContactPerson());
                            ps.setString(7, order.getContactMobile());
                            ps.setString(8, order.getProvince() != null ? order.getProvince() : "");
                            ps.setString(9, order.getCity() != null ? order.getCity() : "");
                            ps.setString(10, order.getArea() != null ? order.getArea() : "");
                            ps.setString(11, order.getAddress() != null ? order.getAddress() : "");
                            ps.setString(12, "");
                            ps.setString(13, order.getStatusStr());
                            ps.setInt(14, order.getStatus());
                            ps.setInt(15, 0);
                            ps.setLong(16, System.currentTimeMillis() / 1000);
                            ps.setLong(17, order.getOrderTime());
                            return ps;
                        }
                    }, keyHolder);

                    Long orderId = keyHolder.getKey().longValue();

                    /*******************2、添加order_item**************************/
                    //添加订单明细
                    String itemSQL = "INSERT INTO dc_pipi_order_items (orderId,itemAmount,erpGoodsId,goodsTitle,goodsNumber,goodsImg,erpGoodsSpecId,specNumber,skuInfo,price,quantity) VALUE (?,?,?,?,?,?,?,?,?,?,?)";
                    for (var item : order.getItems()) {
                        //查询商品SKU

                        Integer erpGoodsSpecId = 0;
                        double itemAmount = item.getPrice().doubleValue() * item.getQuantity();

                        jdbcTemplate.update(itemSQL, orderId, itemAmount,item.getGoodsId(), item.getGoodsTitle(), item.getGoodsNumber(), item.getGoodsImg()
                                ,erpGoodsSpecId, item.getSpecNumber(),item.getSkuInfo()
                                ,  item.getPrice(), item.getQuantity());
                    }

                    totalInsert++;//新增成功

                } catch (Exception e) {
                    totalError++;
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return new ResultVo<>(EnumResultVo.SystemException, "系统异常：" + e.getMessage(),"");
                }
            }
        }
        String msg = "新增成功：" + totalInsert + "，新增失败：" + totalError + "，已存在：" + totalExist;
////        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return new ResultVo<>(EnumResultVo.SUCCESS, "SUCCESS", msg);
//    }
    }


}
